package com.cari.oa.controller;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.CommentEntity;
import com.cari.oa.domain.MarketProjectEntity;
import com.cari.oa.domain.SysDeptEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.CommentService;
import com.cari.oa.service.MarketProjectService;
import com.cari.oa.service.SysDeptService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.DateUtils;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

@Controller
@SessionAttributes({"username","provinces"})
public class ProjectController extends BaseDownloadController {
	
	@Resource
    private MarketProjectService marketProjectService;
    @Resource
    private CommentService commentService;
    @Resource
    private SysDictItemService sysDictItemService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
	private AttachmentService attachmentService;
    
    public static final String MODULE_NAME = "SYS_USER_MANAGE";

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @RequestMapping("/pjcost/project/list.do")
    public String list(@ModelAttribute("provinces") Map<String, String> provinces, Integer sort, String applyUserCN,
    		String name, String province, Date applyTime, String status, Integer curPage, ModelMap modelMap) {
    	 if(curPage == null) curPage = 1;
    	 if(sort == null) sort = 0;
    	 List<MarketProjectEntity> projectList = new ArrayList<MarketProjectEntity>();
    	 long totalRecords = 0;
    	 String applyUserEN = null;
         if(StrUtils.isEmpty(province)){
        	  projectList = marketProjectService.getPage(name, provinces.keySet(), applyUserCN, applyUserEN, applyTime, status, sort, curPage, Contants.PAGE_SIZE);
        	  totalRecords = marketProjectService.getCount(name, provinces.keySet(), applyUserCN, applyUserEN, applyTime, status);
         }else{
        	  projectList = marketProjectService.getPage(name, province, applyUserCN, applyUserEN, applyTime, status, sort, curPage, Contants.PAGE_SIZE);
        	  totalRecords = marketProjectService.getCount(name, province, applyUserCN, applyUserEN, applyTime, status);
         }
         long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
         
         Set<String> projectIds = getProjectIds(projectList);
         List<Map<String, Date>> maxDateList = commentService.getMaxDateList(CommentService.CMT_PRJ, projectIds);
         List<SysUserEntity> userList = sysUserService.getAll();
         
         modelMap.addAttribute("userList", userList);
         modelMap.addAttribute("maxDateList", maxDateList);
         modelMap.addAttribute("projectList", projectList);
         modelMap.addAttribute("provinces", provinces);
         modelMap.addAttribute("curPage", curPage);
         modelMap.addAttribute("totalPage", totalPage);
         modelMap.addAttribute("totalRecords", totalRecords);

         modelMap.addAttribute("name", name);
         modelMap.addAttribute("province", province);
         modelMap.addAttribute("status", status);
         modelMap.addAttribute("sort", sort);
         modelMap.addAttribute("applyUserCN", applyUserCN);
    	
        return "pjcost/project/list";
    }
    
    @RequestMapping(value = "/pjcost/project/view.do", method = RequestMethod.GET)
    public String enterView(String id, String qs, ModelMap modelMap) {
    	MarketProjectEntity project = marketProjectService.getById(id);
    	SysUserEntity user = sysUserService.getByEnname(project.getApplyUser());
    	List<CommentEntity> comments = commentService.getListByObjID(id, CommentService.CMT_PRJ); 
    	List<SysDictItemEntity> provincesList = sysDictItemService.getItemsByGroupName("province");
    	List<SysUserEntity> users = sysUserService.getAll();
    	String[] operators = project.getOperator().split(",");
    	List<String> operatorsEN = Arrays.asList(operators);
    	List<String> operatorsCN = new ArrayList<String>();
    	for(SysUserEntity u: users){
    		if(operatorsEN.contains(u.getEnname())) operatorsCN.add(u.getCnname());
    	}
    	StringBuilder operator = new StringBuilder();
    	for (int i = 0; i < operatorsCN.size(); i++) {
			if(i == (operatorsCN.size() - 1)){
				operator.append(operatorsCN.get(i));
			}else{
				operator.append(operatorsCN.get(i)+",");
			}
		}
    	project.setOperator(operator.toString());
    	
    	List<AttachmentEntity> attachList = attachmentService.getByObjectId(id);
    	
    	modelMap.addAttribute("user", user);
    	modelMap.addAttribute("provincesList", provincesList);
    	modelMap.addAttribute("attachList", attachList);
    	modelMap.addAttribute("comments", comments);
    	modelMap.addAttribute("project", project);
        modelMap.addAttribute("qs", qs);
        return "pjcost/project/view";
    } 
    
    @RequestMapping(value = "/pjcost/project/view.do", method = RequestMethod.POST)
    @ResponseBody
    public String postview(@ModelAttribute("username") String username, String qs,
    		@Valid CommentEntity comment, BindingResult result) {
    	if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
    	comment.setUserEnname(username);
    	SysUserEntity user = sysUserService.getByEnname(username);
    	comment.setUserCnname(user.getCnname());
    	comment.setCreateTime(new Date());
    	
    	commentService.insert(comment); 
    	
    	HashMap<String, String> resultMap = new HashMap<String, String>();
    	resultMap.put("username", comment.getUserCnname());
    	resultMap.put("createtime", DateUtils.date2Str(comment.getCreateTime(), DateUtils.NORMAL_FORMAT));
    	resultMap.put("content", comment.getContent());
    	
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增项目留言");
        return JSON.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/pjcost/project/insert.do", method = RequestMethod.GET)
    public String enterInsert(@ModelAttribute("provinces") Map<String, String> provinces, String qs, 
    		@ModelAttribute("username") String username, ModelMap modelMap) {
        SysUserEntity user = sysUserService.getByEnname(username);
        List<SysUserEntity> users = sysUserService.getAll();
        List<SysDeptEntity> depts = sysDeptService.getAll();
        
    	modelMap.addAttribute("usercnname", user.getCnname());
    	modelMap.addAttribute("users", users);
    	modelMap.addAttribute("depts", depts);
    	modelMap.addAttribute("provinces", provinces);
    	modelMap.addAttribute("qs", qs);
        return "pjcost/project/insert";
    }
    
    @RequestMapping(value = "/pjcost/project/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid MarketProjectEntity marketProjectEntity, BindingResult result) {
    	if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
    	String str = null;
    	marketProjectEntity.setCode(username+DateUtils.date2Str(new Date(), "yyMMdd")+
    			 String.valueOf(marketProjectService.getCount(null, str, null, null, DateUtils.str2Date(DateUtils.date2Str(new Date(), "yyyy-MM-dd")+" 00:00:00", DateUtils.NORMAL_FORMAT), null)+1));
    	marketProjectEntity.setApplyTime(new Date());
    	marketProjectEntity.setLastModifyTime(new Date());
    	
    	marketProjectService.insert(marketProjectEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增项目" + marketProjectEntity.getName());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        resultMap.put("projectId", marketProjectEntity.getId());
        return JSON.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/pjcost/project/update.do", method = RequestMethod.GET)
    public String enterEdit(@ModelAttribute("provinces") Map<String, String> provinces, String id, String qs, ModelMap modelMap) {
    	MarketProjectEntity project = marketProjectService.getById(id);
    	List<AttachmentEntity> attachList = attachmentService.getByObjectId(id);
    	
    	SysUserEntity user = sysUserService.getByEnname(project.getApplyUser());
    	List<CommentEntity> comments = commentService.getListByObjID(id, CommentService.CMT_PRJ);
    	List<SysUserEntity> users = sysUserService.getAll();
        List<SysDeptEntity> depts = sysDeptService.getAll();
        String[] operators = project.getOperator().split(",");
    	List<String> operatorsEN = Arrays.asList(operators);
    	List<String> operatorsCN = new ArrayList<String>();
    	List<SysUserEntity> selectUser = new ArrayList<SysUserEntity>();
    	for(SysUserEntity u: users){
    		if(operatorsEN.contains(u.getEnname())){
    			operatorsCN.add(u.getCnname());
    			selectUser.add(u);
    		}
    	}
    	StringBuilder operator = new StringBuilder();
    	for (int i = 0; i < operatorsCN.size(); i++) {
			if(i == (operatorsCN.size() - 1)){
				operator.append(operatorsCN.get(i));
			}else{
				operator.append(operatorsCN.get(i)+",");
			}
		}
    	
    	modelMap.addAttribute("user", user);
    	modelMap.addAttribute("users", users);
    	modelMap.addAttribute("depts", depts);
    	modelMap.addAttribute("selectUser", selectUser);
    	modelMap.addAttribute("operator", operator.toString());
    	modelMap.addAttribute("provinces", provinces);
    	modelMap.addAttribute("attachList", attachList);
    	modelMap.addAttribute("comments", comments);
        modelMap.addAttribute("project", project);
    	modelMap.addAttribute("qs", qs);
        return "pjcost/project/update";
    }
    
    @RequestMapping(value = "/pjcost/project/update.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid MarketProjectEntity marketProjectEntity, BindingResult result) {
    	if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        
    	marketProjectEntity.setLastModifyTime(new Date());
    	
    	marketProjectService.update(marketProjectEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改项目" + marketProjectEntity.getName());
    	return Utils.normalJsonResp();
    }
    public static void main(String[] args) {
		System.out.println(StrUtils.isNotEmpty(new String()));
	}
    
    @RequestMapping(value = "/pjcost/project/delete.do")
    @ResponseBody
    public String delete(String id) {
    	MarketProjectEntity project = marketProjectService.getById(id);
    	project.setStatus("1");
    	marketProjectService.update(project);
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/pjcost/project/resume.do")
    @ResponseBody
    public String resume(String id) {
    	MarketProjectEntity project = marketProjectService.getById(id);
    	project.setStatus("0");
    	marketProjectService.update(project);
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/pjcost/project/getProjectByApplyUser.do")
    @ResponseBody
    public String getProjectByApplyUser(@ModelAttribute("username") String username, boolean isAll) {
    	List<MarketProjectEntity> projects = null;
    	if(isAll)
    		projects = marketProjectService.getProjectByApplyUser(null);
    	else
    		projects = marketProjectService.getProjectByApplyUser(username);
    	StringBuffer sb = new StringBuffer("[");
    	for(int i= 0 ; i < projects.size();i++)
    	{
    		if(i == projects.size()-1 )
    			sb.append(projects.get(i).toString()+"]");
    		else
    		    sb.append(projects.get(i).toString()+",");
    	}
        return sb.toString();
    }
    
    @RequestMapping("/pjcost/project/userList.do")
    public String userList(@ModelAttribute("provinces") Map<String, String> provinces, @ModelAttribute("username") String username,
    		Integer	sort, String name, String province, Date applyTime, String status, Integer curPage, ModelMap modelMap) {
    	 if(curPage == null) curPage = 1;
    	 if(sort == null) sort = 0;
    	 List<MarketProjectEntity> projectList = new ArrayList<MarketProjectEntity>();
    	 long totalRecords = 0;
    	 String applyUserEN = username;
    	 String applyUserCN = null;
    	 if(StrUtils.isEmpty(province)){
       	  projectList = marketProjectService.getPage(name, provinces.keySet(), applyUserCN, applyUserEN, applyTime, status, sort, curPage, Contants.PAGE_SIZE);
       	  totalRecords = marketProjectService.getCount(name, provinces.keySet(), applyUserCN, applyUserEN, applyTime, status);
        }else{
       	  projectList = marketProjectService.getPage(name, province, applyUserCN, applyUserEN, applyTime, status, sort, curPage, Contants.PAGE_SIZE);
       	  totalRecords = marketProjectService.getCount(name, province, applyUserCN, applyUserEN, applyTime, status);
        }
         long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
         
         Set<String> projectIds = getProjectIds(projectList);
         List<Map<String, Date>> maxDateList = commentService.getMaxDateList(CommentService.CMT_PRJ, projectIds);
         List<SysUserEntity> userList = sysUserService.getAll();
         
         modelMap.addAttribute("userList", userList);
         modelMap.addAttribute("maxDateList", maxDateList);
         modelMap.addAttribute("projectList", projectList);
         modelMap.addAttribute("provinces", provinces);
         modelMap.addAttribute("curPage", curPage);
         modelMap.addAttribute("totalPage", totalPage);
         modelMap.addAttribute("totalRecords", totalRecords);

         modelMap.addAttribute("name", name);
         modelMap.addAttribute("province", province);
         modelMap.addAttribute("status", status);
         modelMap.addAttribute("sort", sort);
    	
        return "pjcost/project/userList";
    }
    
    @RequestMapping("/pjcost/project/upload.do")
	public void upload(@ModelAttribute("username") String username,HttpServletRequest request,HttpServletResponse response,BindingResult result) {
		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
		multipartRequest.setAttribute("ObjectType",AttachmentService.PROJECT_ATTACHMENT_TYPE);
		multipartRequest.setAttribute("ObjectId",multipartRequest.getParameter("projectId"));
		super.upload(username, multipartRequest);
	}
    
    @RequestMapping("/pjcost/project/download.do")
	public void download(String id,HttpServletRequest request, HttpServletResponse response) {
    	AttachmentEntity att = attachmentService.getById(id);
		super.download(att.getName(), att.getPath(), request, response);
	}
    
    private Set<String> getProjectIds(List<MarketProjectEntity> projects) {
    	Set<String> projectIds = new HashSet<String>();
    	for (MarketProjectEntity p  : projects) {
			projectIds.add(p.getId());
		}
		return projectIds;
	}
    
    @RequestMapping("/pjcost/project/report.do")
    public void report(@ModelAttribute("provinces") Map<String, String> provinces, Integer sort, String applyUserCN,
    		String name, String province, Date applyTime, String status, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	 if(sort == null) sort = 0;
    	 List<MarketProjectEntity> projectList = new ArrayList<MarketProjectEntity>();
    	 String applyUserEN = null;
         if(StrUtils.isEmpty(province)){
        	  projectList = marketProjectService.search(name, provinces.keySet(), applyUserCN, applyUserEN, applyTime, status, sort);
         }else{
        	  projectList = marketProjectService.search(name, province, applyUserCN, applyUserEN, applyTime, status, sort);
         }
         
         Set<String> projectIds = getProjectIds(projectList);
         List<Map<String, Date>> maxDateList = commentService.getMaxDateList(CommentService.CMT_PRJ, projectIds);
         Map<String, String> maxDateMap = new HashMap<String, String>();
         for (Map<String, Date> map : maxDateList) {
			Object obj = map.get("objectId");
			String objectId = obj.toString();
			maxDateMap.put(objectId, DateUtils.date2Str(map.get("createTime"), DateUtils.NORMAL_FORMAT));
		}
         
         List<SysUserEntity> userList = sysUserService.getAll();
         Map<String, String> userMap = new HashMap<String, String>();
         for (SysUserEntity sysUserEntity : userList) {
			userMap.put(sysUserEntity.getEnname(), sysUserEntity.getCnname());
		}

         HSSFWorkbook workbook = new HSSFWorkbook(); //新建一个工作簿
		   HSSFSheet sheet = workbook.createSheet();//创建一个工作表
		   sheet.setColumnWidth((short)0, (short)2000);
		   sheet.setColumnWidth((short)1, (short)10000);
		   sheet.setColumnWidth((short)2, (short)5000);
		   sheet.setColumnWidth((short)3, (short)2000);
		   sheet.setColumnWidth((short)4, (short)5000);
		   sheet.setColumnWidth((short)5, (short)2000);
		   sheet.setColumnWidth((short)6, (short)5000);
		   HSSFRow row = sheet.createRow((short)0);
		   HSSFCell cell = row.createCell((short) 0);
		   cell.setCellValue(new HSSFRichTextString("省份"));
		   cell = row.createCell((short) 1);
		   cell.setCellValue(new HSSFRichTextString("项目名称"));
		   cell = row.createCell((short) 2);
		   cell.setCellValue(new HSSFRichTextString("项目编码"));
		   cell = row.createCell((short) 3);
		   cell.setCellValue(new HSSFRichTextString("申请人"));
		   cell = row.createCell((short) 4);
		   cell.setCellValue(new HSSFRichTextString("申报时间"));
		   cell = row.createCell((short) 5);
		   cell.setCellValue(new HSSFRichTextString("状态"));
		   cell = row.createCell((short) 6);
		   cell.setCellValue(new HSSFRichTextString("最新回复时间"));
		   //sheet.createFreezePane(2,2);
		   short index = 0;
		   for ( MarketProjectEntity project : projectList) {
				   row = sheet.createRow(++index);//创建一行
				   cell = row.createCell((short) 0);//创建一个单元格
				   cell.setCellValue(new HSSFRichTextString(provinces.get(project.getProvince())));
				   cell = row.createCell((short) 1);
				   cell.setCellValue(new HSSFRichTextString(project.getName()));
				   cell = row.createCell((short) 2);
				   cell.setCellValue(new HSSFRichTextString(project.getCode()));
				   cell = row.createCell((short) 3);
				   cell.setCellValue(new HSSFRichTextString(userMap.get(project.getApplyUser())));
				   cell = row.createCell((short) 4);
				   cell.setCellValue(new HSSFRichTextString(DateUtils.date2Str(project.getApplyTime(), DateUtils.NORMAL_FORMAT)));
				   cell = row.createCell((short) 5);
				   if(project.getStatus().equals("0"))
					   cell.setCellValue(new HSSFRichTextString("正常"));
				   else
					   cell.setCellValue(new HSSFRichTextString("注销"));
				   cell = row.createCell((short) 6);
				   cell.setCellValue(new HSSFRichTextString(maxDateMap.get(project.getId())));
			}
		   response.setContentType("application/vnd.ms-excel");
		   String str = "项目列表.xls";
		   if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
			   str = new String(str.getBytes("UTF-8"), "ISO8859-1");
		   }else {
			   str = toUtf8String(str);
			   response.setContentType("application/vnd.ms-excel; charset=utf-8"); 
		   }
		   response.setHeader("Content-Disposition",
				   "attachment;filename="+str);
		   response.setHeader("Content-Transfer-Encoding","binary");     
		   response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");     
		   response.setHeader("Pragma", "public");  
		   OutputStream out=response.getOutputStream();
		   workbook.write(out);
		   out.flush();
		   out.close();
    }
    
    /**
	  * 转化utf8
	  * 
	  * @param s
	  * @return
	  * guotingting 2013-1-7 上午11:33:28
	  */
	 private String toUtf8String(String s){ 
	     StringBuffer sb = new StringBuffer(); 
	       for (int i=0;i<s.length();i++){ 
	          char c = s.charAt(i); 
	          if (c >= 0 && c <= 255){sb.append(c);} 
	        else{ 
	        byte[] b; 
	         try { b = Character.toString(c).getBytes("utf-8");} 
	         catch (Exception ex) { 
	             System.out.println(ex); 
	                  b = new byte[0]; 
	         } 
	            for (int j = 0; j < b.length; j++) { 
	             int k = b[j]; 
	              if (k < 0) k += 256; 
	              sb.append("%" + Integer.toHexString(k).toUpperCase()); 
	              } 
	     } 
	  } 
	  return sb.toString(); 
	}
}

